import asyncio

from metagpt.roles import Role
import re
from metagpt.schema import Message
from metagpt.actions import Action
from metagpt.logs import logger
from src.tools.Translated import Translated

# 待确认是否使用这个
# 初步对java文件进行分析：是否为controller/mapper/。。。。或者是其他的

# 分析的action行为
class Analyse(Action):
    PROMPT_TEMPLATE: str = """
    You are a Code Analysis Engineer, and I need you to analyze the following code, Determine if the class is an entity class
    
    If yes, it return 
    ```true ```
    
    otherwise it returns 
    ```false ```
    with NO other texts,
    
    {code}
    """

    name: str = "CodeAnalysis"

    async def run(self, code: str):
        prompt = self.PROMPT_TEMPLATE.format(code=code)
        print("111")
        # print(code)
        print(prompt)

        rsp = await self._aask(prompt)

        code_text = Analyse.parse_code(rsp)

        return code_text

    # 正则表达式提取需要的结果
    @staticmethod
    def parse_code(rsp):
        pattern = r"```type(.*)```"
        match = re.search(pattern, rsp, re.DOTALL)
        code_text = match.group(1) if match else rsp
        return code_text


class Analyst(Role):
    name: str = "Code Analysis Engineer"
    profile: str = "Analyst"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([Analyse])

    async def _act(self) -> Message:
        logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
        todo = self.rc.todo  # todo will be SimpleWriteCode()

        msg = self.get_memories(k=1)[0]  # find the most recent messages
        code_text = await todo.run(msg.content)
        msg = Message(content=code_text, role=self.profile, cause_by=type(todo))

        return msg


async def main(file_path):
    # file_path = r"../../java\project\backend\src\main\java\com\open\harmony\mapper\ProductMapper.java"
    # 将路径中的"\"转换成"/"
    file_path = Translated(file_path)
    # 提取java文件中的代码
    code = ""
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        for line in lines:
            code += line.strip()
            code += "\n"
    role = Analyst()
    logger.info(code)
    result = await role.run(code)
    return result



def class_main(file_path):
    resdata = asyncio.run(main(file_path))
    return resdata


if __name__ == '__main__':
    file_path = r"../../java\project\backend\src\main\java\com\open\harmony\entity\Order.java"
    # asyncio.run(main(file_path))
    class_main(file_path)
    # main()
